package com.gylang.print.richtext.processor;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.img.ImgUtil;
import cn.hutool.core.util.NumberUtil;
import cn.hutool.core.util.ReUtil;
import cn.hutool.core.util.StrUtil;
import com.gylang.print.pdf.util.PdfUtil;
import com.gylang.print.richtext.Coords;
import com.gylang.print.richtext.pdf.RichPdfRender;
import com.gylang.print.richtext.resolver.StyleResolver;
import com.gylang.print.richtext.component.RichBox;
import com.gylang.print.richtext.component.BaseRichImage;
import com.gylang.print.richtext.component.BaseRich;
import org.apache.pdfbox.pdmodel.graphics.image.PDImageXObject;
import org.jsoup.nodes.Element;

import java.io.IOException;
import java.util.List;

/**
 * @author gylang
 * data 2021/7/13
 */
public class ImageProcessor implements StyleResolver, RichPdfRender<BaseRichImage> {
	@Override
	public boolean resolve(Element element, List<BaseRich> component, BaseRich parent) {

		if ("img".equalsIgnoreCase(element.tagName())) {
			BaseRichImage richImage = new BaseRichImage();
			richImage.copyStyle(parent);
			// 获取样式
			String style = element.attr("style");
			richImage.setSrc(element.attr("src"));
			richImage.setHref(element.attr("data-href"));
			richImage.setAlt(element.attr("alt"));
			// 获取长宽 判断是px 还是%
			float height = NumberUtil.parseFloat(element.attr("height"));
			if (0 < height) {
				// px
				float width = NumberUtil.parseFloat(element.attr("width"));
				richImage.setIfNoNull(BaseRichImage.WIDTH, width);
				richImage.setIfNoNull(BaseRichImage.HEIGHT, height);
			} else {
				// %
				richImage.setPercent(true);
				float width = NumberUtil.parseFloat(StrUtil.removeAll(element.attr("width"), "%"));
				richImage.setIfNoNull(BaseRichImage.WIDTH, width);
			}
			if (StrUtil.isNotEmpty(style)) {
				List<String> fontSizes = ReUtil.findAllGroup1("font-size: (\\d+)px", style);
				String fontSize = CollUtil.getFirst(fontSizes);
				if (StrUtil.isNotEmpty(fontSize)) {
					richImage.setIfNoNull(BaseRich.FONT_SIZE, Float.parseFloat(fontSize));
				}

			}
			component.add(richImage);
			return true;
		}

		return false;
	}

	@Override
	public Coords render(Coords lastNodeCoords, RichBox box, BaseRichImage richImage) {

		float width = richImage.width();
		float height = richImage.height();

		// 渲染图片

		try {
			PDImageXObject imageObject = PDImageXObject.createFromByteArray(box.getDocument(), ImgUtil.toBytes(richImage.getImage(), ImgUtil.IMAGE_TYPE_PNG), "imgUrl");

			PdfUtil.writeImg(box.getContentStream(), imageObject, lastNodeCoords.ex(), lastNodeCoords.ey(), width, height);
		} catch (IOException e) {
			e.printStackTrace();
		}

		return Coords.of(0, lastNodeCoords.ey() - height);
	}
}
